# -*- coding:utf-8 -*-

import urllib2
from PyQt4.QtCore import *

class DownloadThread(QThread):
    def __init__(self):
        QThread.__init__(self)
        self.imageData = ""

    def setDate(self,date):
        self.date = QDate(date)

    def run(self):
        self.emit(SIGNAL("started()"))

        self.imageData = ""
        comicUrl = "http://pag.csail.mit.edu/~adonovan/dilbert/"

        if self.date == QDate.currentDate():
            comicUrl += "today.gif"
        else:
            comicUrl += "dilbert-"+self.date.toString("dd-MM-yyyy")+".gif"

        try:
            request = urllib2.urlopen(str(comicUrl))
        except urllib2.HTTPError, e:
            if e.code == 404:
                self.emit(SIGNAL("gotError(const QString&)"), "Requested day doesn't exist")
            else:
                self.emit(SIGNAL("gotError(const QString&)"), e.read())
            self.emit(SIGNAL("done(bool)"), True)
            return

        headers = request.info()
        size = int(headers['Content-Length'])
        i = 0
        block_size = 4096

        while i < size:
            self.imageData += request.read(block_size)
            i += block_size
            self.emit(SIGNAL("updateProgress(int,int)"),i,size)

        request.close()
        self.emit(SIGNAL("done(bool)"),False)
